package com.buddy.sds.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.buddy.sds.auth.entity.SystemPermission;
import com.buddy.sds.auth.entity.SystemRole;
import com.buddy.sds.auth.mapper.ISystemRoleMapper;
import com.buddy.sds.auth.service.ISystemPermissionService;
import com.buddy.sds.auth.service.ISystemRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
@Primary
@Service
public class SystemRoleServiceImpl extends ServiceImpl<ISystemRoleMapper, SystemRole> implements ISystemRoleService {

    @Autowired
    private ISystemPermissionService permissionService;

    @Override
    public List<SystemRole> getRoleListByUser(String user_id,boolean includePermission) {

        List<SystemRole> roles =  baseMapper.getRoleListByUser(user_id);

        if(includePermission){
            if(roles != null && !roles.isEmpty()){

                roles.forEach(role->{

                    List<SystemPermission> permissions = permissionService.getPermissionListByRole(role.getRoleId());

                    if(permissions != null && !permissions.isEmpty()){
                        role.setPermissions(permissions);
                    }

                });
            }
        }
        return roles;
    }

    @Override
    public List<String> getRoleNameList(String user_id) {
        List<SystemRole> roles = getRoleListByUser(user_id,false);

        List<String> result = new ArrayList<>();

        roles.forEach(r->{
            result.add(r.getRoleName());
        });

        return result;
    }

    @Override
    public boolean roleExists(String role_name) {

        SystemRole role = baseMapper.selectOne(new QueryWrapper<SystemRole>().eq("role_name",role_name));

        return role != null;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteCascade(String role_id) {

        if(removeById(role_id)){
            baseMapper.deletePermissionRelations(role_id);
            baseMapper.deleteUserRelations(role_id);
        }
    }


}
